<template>
  <view :style="colorStyle">
    <block v-if="!isLoading">
      <!-- #ifdef MP-WEIXIN -->
      <view class="" style="height: 100rpx"> </view>
      <!-- #endif -->
      <x-skeleton type="banner" :loading="true">
        <view>我是轮播图</view>
      </x-skeleton>
      <x-skeleton type="menu" :loading="true">
        <view>我是轮播图</view>
      </x-skeleton>
      <x-skeleton type="list" :loading="true">
        <view>我是轮播图</view>
      </x-skeleton>
      <x-skeleton
        type="waterfall"
        v-for="(item, index, key) in 100"
        :key="'waterfall' + index"
        :loading="true"
      >
        <view>我是轮播图</view>
      </x-skeleton>
    </block>
    <view v-if="isLoading">
      <view
        class="infobox1 flex aitems between"
        v-if="addressinfo.id == undefined"
        @click="gourl(`/pages/user/address?addStatus=1`)"
      >
        <view class="block1 c1F1F1F f32 fontWeight"> 添加收货地址 </view>
        <image src="@/static/img18.png" mode=""></image>
      </view>
      <view
        class="infobox11 flex aitems between"
        v-else
        @click="gourl(`/pages/user/address?addStatus=1`)"
      >
        <view class="block1">
          <view class="tip1 c1F1F1F f32 fontWeight">
            {{ addressinfo.province }} {{ addressinfo.city }}
            {{ addressinfo.district }} {{ addressinfo.address }}
          </view>
          <view class="tip2 c858585 f28 flex aitems">
            <view class="">
              {{ addressinfo.consignee }}
            </view>
            <view class="tip22">
              {{ addressinfo.mobile }}
            </view>
          </view>
        </view>
        <image src="@/static/img18.png" mode=""></image>
      </view>
      <view
        class="infobox2"
        v-for="(item, index, key) in info.sellerCartList"
        :key="key"
      >
        <view class="block1 flex aitems">
          <image class="icon1" :src="item.sellerLogo" mode="aspectFill"></image>
          <view class="name c1F1F1F f32 fontWeight">
            {{ item.sellerName }}
          </view>
          <!-- <image class="icon2" src="@/static/img15.png" mode=""></image> -->
        </view>
        <view class="block2">
          <view
            class="list flex"
            v-for="(items, indexs, keys) in item.sellerCartItemList"
            :key="keys"
          >
            <image :src="items.goodsImg" mode="aspectFill"></image>
            <view class="info1">
              <view class="tipbox1 flex aitems between">
                <view class="tip1 ellipsis1 c1F1F1F f28">
                  {{ items.goodsName }}
                </view>
                <view class="tip2 c858585 f24"> X{{ items.goodsNum }} </view>
              </view>
              <view class="tipbox2 c858585 f24">
                {{
                  items.goodsSpec
                    .replace(/{/g, "")
                    .replace(/}/, "")
                    .replace(/"/g, "")
                }}
              </view>
              <view class="tipbox3 flex aitems between">
                <view class="tip1 c1F1F1F fontWeight">
                  <text class="f24">￥</text>
                  <text class="f32">{{ items.goodsPrice.toFixed(2) }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="block3 flex aitems between" style="position: relative">
          <picker
            class="avatar-wrapper"
            mode="selector"
            :range="item.logisticsTypeList"
            range-key="name"
            @change="logisticsTypeListChange($event, index)"
          >
            <view class="avatar-wrapper"></view>
          </picker>
          <view class="info1 c858585 f28"> 配送方式 </view>
          <view class="info2 flex aitems c1F1F1F f28 fontWeight">
            {{ logisticsType[item.logisticsType] }}
            <image src="@/static/img15.png" mode=""></image>
          </view>
        </view>
        <view
          class="block4 flex aitems between"
          v-if="item.logisticsType == logisticsType.selfRaising"
          @click="openLocation(item, index)"
          style="position: relative"
        >
          <view class="info1" v-if="item.sellerAddressInfo.address">
            <block v-if="item.sellerAddressInfo.address.id">
              <view class="tip1 f36 c1F1F1F fontWeight">
                {{ item.sellerAddressInfo.address.consignee }} -
                {{ item.sellerAddressInfo.address.mobile }}
              </view>
              <view class="tip2 c1F1F1F f28">
                {{ item.sellerAddressInfo.address.province
                }}{{ item.sellerAddressInfo.address.city
                }}{{ item.sellerAddressInfo.address.district
                }}{{ item.sellerAddressInfo.address.address }}
              </view>
            </block>
            <view class="tip1 f32 c1F1F1F fontWeight" v-else>
              请选择自提地址
            </view>
            <view
              class="tip2 c1F1F1F f28"
              v-if="item.sellerAddressInfo.pickOpenDate"
            >
              营业时间：{{ item.sellerAddressInfo.pickOpenDate }}
              {{ item.sellerAddressInfo.pickOpenTime }}
            </view>
          </view>
          <u-icon name="arrow-right" size="20"></u-icon>
          <!-- <u-icon name="map-fill" size="20" color="var(--view-theme)"></u-icon> -->
        </view>
        <view
          class="block4 flex aitems between"
          v-if="item.logisticsType == logisticsType.sameCityDistribution"
          style="position: relative"
        >
          <u-picker
            style="flex: 0"
            :show="item.dateShow"
            :ref="'uPicker' + index"
            :columns="item.columnsList"
            @confirm="confirm($event, index)"
            @change="changeHandler($event, index)"
            @cancel="dateShowHideChange(index)"
          ></u-picker>

          <block v-if="item.sellerDeliveryConfig.isOpenTiming == 1"
            ><view class="info1" @click="dateShowChange(item, index)">
              <view class="tip1 f32 c1F1F1F fontWeight"> 请选择配送时间 </view>
              <view class="tip2 f26 c666 flex" v-if="item.date && item.time">
                <view>配送时间：{{ item.date }}</view>
                <view style="margin-left: 20rpx">{{ item.time }}</view>
              </view>
            </view>
            <u-icon name="arrow-right" size="20"></u-icon
          ></block>

          <block v-if="item.sellerDeliveryConfig.isOpenTiming == 0"
            ><view class="info1" style="width: 90%">
              <view class="tip1 f32 c1F1F1F fontWeight"> 立马配送 </view>
              <view class="tip2 f26 c666 flex">
                <view
                  >配送时间：{{ getCurrentAndNextHourTimesObj.start[0] }}</view
                >
                <view style="margin-left: 20rpx"
                  >{{ getCurrentAndNextHourTimesObj.start[1] }} -
                  {{ getCurrentAndNextHourTimesObj.end[1] }}</view
                >
              </view>
            </view>
          </block>
        </view>
        <view
          class="block5 flex aitems between"
          v-if="item.logisticsType == logisticsType.logistics"
        >
          <view class="info1 c858585 f28"> 运费 </view>
          <view class="info2 flex aitems c1F1F1F f28 fontWeight">
            ￥{{ item.transportFee }}
          </view>
        </view>
        <view class="block5 flex aitems between">
          <view class="info1 c858585 f28"> 店铺优惠 </view>
          <view
            class="info2 flex aitems cDD5C5C f28 fontWeight"
            v-if="Number(item.totalPreferential) > 0"
          >
            -￥{{ item.totalPreferential }}
            <!-- <image src="@/static/img15.png" mode=""></image> -->
          </view>
        </view>
        <view class="block6">
          <view
            class="cell flex aitems between"
            @click="sellerCoupon(item, index)"
          >
            <view class="info1 c858585 f28"> 优惠券 </view>
            <view
              class="info2 flex aitems cDD5C5C f28 fontWeight"
              v-if="
                item.couponsList.length !== 0 && item.couponinfo.id == undefined
              "
            >
              {{ item.couponsList.length }}张可用
              <image src="@/static/img15.png" mode=""></image>
            </view>
            <view
              class="info2 flex aitems cDD5C5C f28 fontWeight"
              v-if="item.couponinfo.id"
            >
              -￥{{ item.couponinfo.money }}
              <image src="@/static/img15.png" mode=""></image>
            </view>
            <view
              class="info2 flex aitems c858585 f28"
              v-if="item.couponsList.length == 0"
            >
              暂无优惠券可用
              <image src="@/static/img15.png" mode=""></image>
            </view>
          </view>
          <view
            class="cell flex aitems between"
            v-for="(items, indexs, keys) in item.deductPublicityDetail"
            :key="keys"
          >
            <view class="info1 c858585 f28">
              {{ items.key }}
            </view>
            <view class="info2 flex aitems cDD5C5C f28 fontWeight">
              -￥{{ Number(items.value) < 0 ? 0 : items.value }}
            </view>
          </view>
        </view>
        <view class="block5">
          <view class="info1 c858585 f28"> 备注 </view>
          <view class="textarea">
            <textarea
              placeholder="请输入您的备注信息"
              placeholder-class="c858585 f28"
              class="c1F1F1F f28"
              v-model="item.remarks"
            ></textarea>
          </view>
        </view>
      </view>
      <view class="infobox3">
        <view class="block1 flex aitems between">
          <view class="info1 c858585 f28"> 商品总价 </view>
          <view class="info2 c1F1F1F f28 fontWeight">
            ￥{{ info.goodsPriceTotal || 0 }}
          </view>
        </view>
        <view class="block1 flex aitems between">
          <view class="info1 c858585 f28"> 快递运费 </view>
          <view class="info2 c1F1F1F f28 fontWeight">
            ￥{{ info.transportFee || 0 }}
          </view>
        </view>
        <view class="block1 flex aitems between">
          <view class="info1 c858585 f28"> 平台优惠 </view>
          <view
            class="info2 cDD5C5C f28 flex aitems fontWeight"
            v-if="Number(info.totalPreferential) > 0"
          >
            -￥{{ info.totalPreferential }}
            <!-- <image src="@/static/img15.png" mode=""></image> -->
          </view>
        </view>
        <view class="block6">
          <view class="cell flex aitems between" @click="sellerCoupon(info)">
            <view class="info1 c858585 f28"> 优惠券 </view>
            <view
              class="info2 flex aitems cDD5C5C f28 fontWeight"
              v-if="info.couponsList.length !== 0 && couponinfo.id == undefined"
            >
              {{ info.couponsList.length }}张可用
              <image src="@/static/img15.png" mode=""></image>
            </view>
            <view
              class="info2 flex aitems cDD5C5C f28 fontWeight"
              v-if="couponinfo.id"
            >
              -￥{{ couponinfo.money }}
              <image src="@/static/img15.png" mode=""></image>
            </view>
            <view
              class="info2 flex aitems c858585 f28"
              v-if="info.couponsList.length == 0"
            >
              暂无优惠券可用
              <image src="@/static/img15.png" mode=""></image>
            </view>
          </view>
        </view>
        <view
          class="block2 c858585 f28"
          v-if="configInfo.isOpenIntegral == '1'"
        >
          积分支付（剩余：{{ user.integral }}积分）
        </view>
        <view
          class="block3 flex aitems between"
          v-if="configInfo.isOpenIntegral == '1'"
        >
          <input
            type="number"
            class="c1F1F1F f28"
            placeholder-class="c858585 f28"
            placeholder="请输入积分"
            v-model="deductIntegral"
            @blur="deductIntegralBlurChange"
          />
          <view class="themeColor f24 fontWeight">
            {{ info.deductIntegralMoney }}元
          </view>
        </view>
        <!-- <view class="block2 c858585 f28">
				余额支付（剩余：{{ user.money }}余额）
			</view> -->
        <!-- <view class="block3 flex aitems between">
				<input type="digit" class="c1F1F1F f28" placeholder-class="c858585 f28" placeholder="请输入余额"
					v-model="deductMoney" @blur="deductMoneyBlurChange" />
				<view class="themeColor f24 fontWeight">
					{{ info.deductMoney }}元
				</view>
			</view> -->
        <view class="block2 c858585 f28"> 微信支付 </view>
        <view class="block3 themeColor f28 fontWeight">
          ￥{{ info.orderPriceTotal }}
        </view>
      </view>

      <view class="" style="height: 200rpx"> </view>

      <view class="infobox4 flex between">
        <view class="left"> </view>
        <view class="right flex aitems">
          <view class="block1">
            <view class="info1 flex aitems fontWeight">
              <view class="tip1 c1F1F1F f24">
                共{{ info.goodsNumTotal || 0 }}件，合计：
              </view>
              <view class="tip2 cF65B49 f36">
                ￥{{ info.orderPriceTotal || 0 }}
              </view>
            </view>
            <view class="info2 cF65B49 f22">
              共减 ￥{{ info.totalPreferential2 || 0 }}
            </view>
          </view>
          <view class="block2 cfff f32" @click="handlePay"> 立即购买 </view>
        </view>
      </view>

      <u-popup
        mode="bottom"
        :safeAreaInsetBottom="false"
        :show="goodsShow"
        :overlayStyle="{ 'touch-action': 'none' }"
        bgColor="transparent"
        @close="goodsShow = false"
      >
        <view class="popbox1">
          <image
            src="@/static/img56.png"
            class="close"
            mode=""
            @click="goodsShow = false"
          ></image>
          <view class="block1 c1F1F1F f36 fontWeight"> 请选择优惠券 </view>
          <view class="block3">
            <view
              v-for="(item, index, key) in couponList"
              :key="key"
              class="list flex aitems"
              @click.stop="radioChange(index)"
            >
              <view class="left">
                <view class="price">
                  <span class="unit">￥</span>
                  <span class="num">{{ item.money }}</span>
                </view>
                <view class="price1"> 满{{ item.minPrice }}元使用 </view>
                <view class="label">
                  {{ couponsUseType[item.useType] }}
                </view>
              </view>
              <view class="border"></view>
              <view class="right flex aitems between">
                <view class="couponinfo">
                  <view class="name fontWeight">
                    {{ item.name }}
                  </view>
                  <view class="time"> 有效期至 {{ item.endTime }} </view>
                  <view
                    class="log flex aitems"
                    @click.stop="couponDescriptionChange(item)"
                  >
                    <u-icon name="search" size="22" color="#525252"></u-icon>
                    <span>查看使用说明</span>
                  </view>
                </view>
                <view class="couponbtn">
                  <radio
                    :checked="item.isSelect ? true : false"
                    color="var(--view-theme)"
                    style="transform: scale(0.9)"
                  />
                </view>
              </view>
            </view>
            <nodata v-if="couponList.length == 0" />
            <view
              class="nodata tcenter c858585"
              v-if="couponList.length !== 0"
              @click="noUseCoupon"
              >不使用优惠券</view
            >
          </view>
          <view class="btn f32 cfff" @click="couponsChangOk"> 确定 </view>
          <view class="" style="height: 100rpx"> </view>
        </view>
      </u-popup>

      <u-popup
        mode="bottom"
        :safeAreaInsetBottom="false"
        :show="show"
        :overlayStyle="{ 'touch-action': 'none' }"
        bgColor="transparent"
        @close="(show = false), (goodsShow = true)"
      >
        <coupon-description
          :value="couponDetail.brief"
          @closeChange="show = false"
        />
      </u-popup>

      <u-toast ref="uToast"></u-toast>
    </view>

    <sellerAddressListCom
      v-if="sellerAddressShow"
      :addressList="addressList"
      @hideChange="sellerAddressShow = false"
      @addressInfoChange="addressInfoChange"
    />
  </view>
</template>

<script>
import {
  orderConfirm,
  userinfo,
  orderSubmit,
  payOrder,
  config as configApi,
  sellerAddressList,
} from "@/servers/servers.js";
import { HTTP_STATUS, config } from "@/servers/config.js";
import colors from "@/mixins/color";
import sellerAddressListCom from "@/components/sellerAddressList";
import {
  back,
  loading,
  go,
  msg,
  requestPayment,
  requestSubscribeMessage,
} from "../../utils/wxAPI";
import { logisticsType, couponsUseType, payClient } from "@/keys/keys.js";
import {
  getStorage,
  getToken,
  removeStorage,
  setStorage,
} from "../../utils/storage";
import { getEnv } from "@/utils/env.js";
import { pays } from "@/utils/pay";
import {
  getDatesForNextDays,
  getDatesFromDayPlusDays,
  isTimeRangePassed,
  addOneHourToTime,
  addOneMinuteToTime,
  getCurrentAndNextHourTimes,
  canBeScheduled,
  canBeScheduledMinutes,
} from "@/utils/distribution";

export default {
  components: { sellerAddressListCom },
  mixins: [colors],
  data() {
    return {
      dateShow: false,
      columns: [
        ["中国", "美国"],
        ["深圳", "厦门", "上海", "拉萨"],
      ],
      columnData: [
        ["深圳", "厦门", "上海", "拉萨"],
        ["得州", "华盛顿", "纽约", "阿拉斯加"],
      ],
      sellerAddressIndex: null,
      addressList: [],
      sellerAddressShow: false,
      isLoading: false,
      payClient,
      couponList: [],
      logisticsType,
      couponsUseType,
      goodsShow: false,
      show: false,
      options: {},
      deductIntegral: "",
      deductMoney: "",
      couponinfo: {}, //平台优惠券
      addressinfo: {}, //收获地址
      orderShopList: [], //商户信息
      info: {
        sellerCartList: [],
        couponsList: [],
      }, //订单信息
      user: {},
      couponDetail: {}, //使用说明
      isCoupon: 1, //是否使用优惠券
      couponIndex: null, //null操作平台的优惠券，有数值代表操作商户的
      orderNo: "",
      configInfo: {
        isOpenIntegral: "0",
      },
      ispaySuccess: false, //是否已经支付
      getCurrentAndNextHourTimesObj: {
        start: [],
        end: [],
      },
    };
  },
  async onLoad(options) {
    this.options = options;
    this.handleconfigApi();

    /***/
    // console.log(getCurrentAndNextHourTimes());

    // console.log(getCurrentAndNextHourTimes()[0].split(" "));
    // console.log(getCurrentAndNextHourTimes()[1].split(" "));
    this.getCurrentAndNextHourTimesObj = {
      start: getCurrentAndNextHourTimes()[0].split(" "),
      end: getCurrentAndNextHourTimes()[1].split(" "),
    };
    // console.log(this.getCurrentAndNextHourTimesObj);
  },
  async onShow() {
    if (getStorage("addressInfo")) {
      this.addressinfo = getStorage("addressInfo");
      removeStorage("addressInfo");
    }
    if (getToken()) {
      this.userinfo();
      if (!this.ispaySuccess) {
        await this.orderConfirm();
        console.log(this.orderShopList);
        if (this.orderShopList.length == 0) {
          await this.orderConfirm();
        }
      }
    }
  },
  methods: {
    async handleconfigApi() {
      let { data } = await configApi({
        key: "shop",
      });
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        this.configInfo = JSON.parse(data.data);
      }
    },
    async userinfo() {
      let { data } = await userinfo();
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        this.user = data.data;
      }
    },
    async orderConfirm() {
      if (this.options.ids || this.options.id) {
        loading();
        let { data } = await orderConfirm({
          addrId: this.addressinfo?.id ? this.addressinfo.id : 0,
          cartIds: this.options.ids ? this.options.ids.split(",") : [],
          couponId: this.couponinfo?.id
            ? this.couponinfo.id
            : this.isCoupon
            ? ""
            : 0,
          deductIntegral: this.deductIntegral, //积分抵扣
          deductMoney: this.deductMoney, //余额抵扣
          orderItem: {
            goodsId: this.options.id,
            goodsNum: this.options.num,
            goodsSkuId: this.options.skuid,
          },
          orderShopList: this.orderShopList,
        });
        if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
          let info = data.data;
          this.filterData(info);
          this.info = info;
          setTimeout(() => {
            this.isLoading = true;
          }, 500);
        } else {
          this.deductIntegral = "";
          this.deductMoney = "";
          back();
        }
        uni.hideLoading();
      }
    },
    filterData(info) {
      console.log(info);

      if (info.couponsList.length == 0) {
        this.couponinfo = {};
      }

      this.deductIntegral = info.deductIntegral > 0 ? info.deductIntegral : "";

      this.deductMoney = info.deductMoney > 0 ? info.deductMoney : "";

      info.totalPreferential = Number(info.deductCouponSystem).toFixed(2);

      info.totalPreferential2 = Number(
        info.deductCouponSeller + info.deductCouponSystem + info.deductPublicity
      ).toFixed(2);

      let orderShopList = [];
      info.sellerCartList.map((item, index) => {
        if (this.info.sellerCartList.length == 0) {
          item.remarks = "";
          item.sellerAddressInfo = { address: {} };
          item.sellerAddressList = [];
        } else {
          item.remarks = this.info.sellerCartList[index].remarks;
          item.sellerAddressInfo =
            this.info.sellerCartList[index].sellerAddressInfo;
          item.sellerAddressList =
            this.info.sellerCartList[index].sellerAddressList;
        }

        /**同城配送*/
        if (item.logisticsType == 3) {
          item.dateShow = false;
          //item.sellerDeliveryConfig配置信息
          if (item.sellerDeliveryConfig.isOpenTiming == 1) {
            /**开启的时间段的配置*/
            //advanceUnit 提前配置 1小时 2小时 3分钟
            let advanceUnit = item.sellerDeliveryConfig.advanceUnit;
            //advanceType 是否提前1否 2是
            let advanceType = item.sellerDeliveryConfig.advanceType;
            if (advanceType == 1) {
              /**获取当天+3天的时间数组*/
              let dateList = [];
              item.sellerDeliveryConfig.timeList.map((date) => {
                dateList.push(`${date.beginTime}-${date.endTime}`);
              });
              let columnData = [];
              getDatesForNextDays(4).map((date) => {
                columnData.push(dateList);
              });
              let columnData0 = [];
              columnData[0].map((items, index) => {
                if (!isTimeRangePassed(items)) {
                  columnData0.push(items);
                }
              });
              columnData[0] = columnData0;
              item.columnsList = [getDatesForNextDays(4), columnData0];
              item.columnData = [columnData];
            } else {
              if (advanceUnit == 1) {
                let advanceValue = item.sellerDeliveryConfig.advanceValue;
                /**提前天数*/
                /**获取延后时间+3天的时间数组*/
                let dateList = [];
                item.sellerDeliveryConfig.timeList.map((date) => {
                  dateList.push(`${date.beginTime}-${date.endTime}`);
                });
                let columnData = [];
                getDatesFromDayPlusDays(advanceValue, 3).map((date) => {
                  columnData.push(dateList);
                });
                let columnData0 = [];
                columnData[0].map((items, index) => {
                  // if (!isTimeRangePassed(items)) {
                  columnData0.push(items);
                  // }
                });
                columnData[0] = columnData0;
                item.columnsList = [
                  getDatesFromDayPlusDays(advanceValue, 3),
                  columnData0,
                ];
                item.columnData = [columnData];
              }
              if (advanceUnit == 2) {
                let advanceValue = item.sellerDeliveryConfig.advanceValue;
                /**提前小时*/
                /**获取延后时间+3天的时间数组*/
                let dateList = [];
                item.sellerDeliveryConfig.timeList.map((date) => {
                  dateList.push(`${date.beginTime}-${date.endTime}`);
                });
                let columnData = [];
                getDatesForNextDays(4).map((date) => {
                  columnData.push(dateList);
                });
                let columnData0 = [];
                columnData[0].map((items, index) => {
                  if (canBeScheduled(items, advanceValue)) {
                    columnData0.push(items);
                  }
                });
                columnData[0] = columnData0;
                item.columnsList = [getDatesForNextDays(4), columnData0];
                item.columnData = [columnData];
              }
              if (advanceUnit == 3) {
                let advanceValue = item.sellerDeliveryConfig.advanceValue;
                /**提前分钟*/
                /**获取延后时间+3天的时间数组*/
                let dateList = [];
                item.sellerDeliveryConfig.timeList.map((date) => {
                  dateList.push(`${date.beginTime}-${date.endTime}`);
                });
                let columnData = [];
                getDatesForNextDays(4).map((date) => {
                  columnData.push(dateList);
                });
                let columnData0 = [];
                columnData[0].map((items, index) => {
                  if (canBeScheduledMinutes(items, advanceValue)) {
                    columnData0.push(items);
                  }
                });
                columnData[0] = columnData0;
                item.columnsList = [getDatesForNextDays(4), columnData0];
                item.columnData = [columnData];
              }
            }
          } else {
            /**立马配送*/
          }
        }

        /***店铺总优惠****/
        item.totalPreferential = Number(
          item.deductCouponSeller + item.deductPublicity
        ).toFixed(2);

        item.logisticsTypeList = [
          {
            name: logisticsType[1],
            value: 1,
          },
        ];
        if (item.sellerIsOpenPick == 1) {
          item.logisticsTypeList.push({
            name: logisticsType[2],
            value: 2,
          });
        }
        if (item.sellerIsOpenDelivery == 1) {
          item.logisticsTypeList.push({
            name: logisticsType[3],
            value: 3,
          });
        }

        let couponId = "";
        item.isCoupon = 0;
        item.couponinfo = {};
        if (item.couponsList.length == 0) {
          item.couponinfo = {};
        }
        item.couponsList.map((items) => {
          if (items.isSelect) {
            couponId = items.id;
            item.couponinfo = items;
            item.isCoupon = 1;
          }
        });

        orderShopList.push({
          couponId: couponId ? couponId : item.isCoupon ? "" : 0,
          logisticsType: item.logisticsType,
          sellerId: item.sellerId,
        });
      });
      this.orderShopList = orderShopList;

      this.addressinfo = info.userAddress;

      this.couponinfo = {};
      info.couponsList.map((item) => {
        if (item.isSelect) {
          this.couponinfo = item;
        }
      });
    },
    async logisticsTypeListChange(e, index) {
      let value =
        this.info.sellerCartList[index].logisticsTypeList[e.detail.value].value;
      this.orderShopList[index].logisticsType = value;
      console.log(value);
      /**请求商户地址列表*/
      // if (value == 2) {
      //   let sellerId = this.info.sellerCartList[index].sellerId;
      //   await this.handleGetSellerAddress(sellerId, index);
      // }
      if (value == 2) {
        this.info.sellerCartList[index].sellerAddressList =
          this.info.sellerCartList[index].sellerPickConfigList;
      }
      await this.orderConfirm();
    },
    async handleGetSellerAddress(sellerId, index) {
      loading();
      let { data } = await sellerAddressList({ sellerId });
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        let list = data.data;
        this.info.sellerCartList[index].sellerAddressList = list;
      }
    },
    async radioChange(index) {
      this.couponList.map((item) => {
        item.isSelect = 0;
      });
      this.couponList[index].isSelect = this.couponList[index].isSelect ? 0 : 1;
      console.log(this.couponList[index].isSelect);
    },
    async couponsChangOk() {
      console.log(this.couponIndex);
      this.couponinfo = {};
      this.couponList.map((item) => {
        if (item.isSelect) {
          if (this.couponIndex == null) {
            this.couponinfo = item;
          } else {
            this.orderShopList[this.couponIndex].couponId = item.id;
          }
        }
      });
      this.goodsShow = false;
      await this.orderConfirm();
    },
    async deductIntegralBlurChange(event) {
      if (event.target.value > this.user.integral) {
        event.target.value = String(this.user.integral);

        this.$refs.uToast.show({
          type: "default",
          message: `您最多可使用${this.user.integral}积分`,
          complete() {},
        });
      }
      this.deductIntegral = event.target.value
        .replace(/[^\d.]/g, "")
        .replace(/^\./g, "")
        .replace(/\.{2,}/g, ".")
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".")
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
      await this.orderConfirm();
    },
    async deductMoneyBlurChange(event) {
      if (event.target.value > this.user.money) {
        event.target.value = String(this.user.money);
      }
      this.deductMoney = event.target.value
        .replace(/[^\d.]/g, "")
        .replace(/^\./g, "")
        .replace(/\.{2,}/g, ".")
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".")
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
      await this.orderConfirm();
    },
    couponDescriptionChange(info) {
      this.couponDetail = info;
      this.goodsShow = false;
      this.show = true;
    },
    sellerCoupon(item, index = null) {
      this.couponIndex = index;
      this.couponList = item.couponsList;
      this.goodsShow = true;
    },
    async noUseCoupon() {
      if (this.couponIndex == null) {
        this.isCoupon = 0;
        this.couponinfo = {};
      } else {
        this.orderShopList[this.couponIndex].couponId = 0;
      }
      this.goodsShow = false;
      await this.orderConfirm();
    },
    async handlePay() {
      // #ifdef MP-WEIXIN
      loading();
      requestSubscribeMessage({
        tmplIds: [
          "Ds9t0xqKmknQoZlozinu03ylvcSfh_FFHIC-NH2rXEc",
          "vlSi0JaXp-8ZuL1GRpBm8JRecROkW7tDRBvdcjA1eT4",
        ],
      }).then(async (res) => {
        this.handleOrderSubmit();
      });
      // #endif
      // #ifdef H5
      this.handleOrderSubmit();
      // #endif
    },
    async handleOrderSubmit() {
      for (let i = 0; i < this.info.sellerCartList.length; i++) {
        if (this.info.sellerCartList[i].logisticsType == 3) {
          if (
            this.info.sellerCartList[i].sellerDeliveryConfig.isOpenTiming == 0
          ) {
            if (!this.getCurrentAndNextHourTimesObj.start[0]) {
              return msg("请选择配送时间");
            }
          }
          if (
            this.info.sellerCartList[i].sellerDeliveryConfig.isOpenTiming == 1
          ) {
            if (!this.info.sellerCartList[i].date) {
              return msg("请选择配送时间");
            }
          }
        }
      }
      let orderShopList = [];
      let getCurrentAndNextHourTimesObj = {
        start: getCurrentAndNextHourTimes()[0].split(" "),
        end: getCurrentAndNextHourTimes()[1].split(" "),
      };
      console.log(getCurrentAndNextHourTimesObj);
      this.info.sellerCartList.map((item, index) => {
        console.log(item);
        orderShopList.push({
          remarks: item.remarks ? item.remarks : "",
          sellerId: item.sellerId,
          sellerAddressId: item.sellerAddressInfo.address.id
            ? item.sellerAddressInfo.address.id
            : 0,
          deliveryDate:
            item.logisticsType == 3
              ? item.sellerDeliveryConfig.isOpenTiming == 0
                ? getCurrentAndNextHourTimesObj.start[0]
                : item.date
              : "",
          deliveryBeginTime:
            item.logisticsType == 3
              ? item.sellerDeliveryConfig.isOpenTiming == 0
                ? getCurrentAndNextHourTimesObj.start[1]
                : item.time.split("-")[0]
              : "",
          deliveryEndTime:
            item.logisticsType == 3
              ? item.sellerDeliveryConfig.isOpenTiming == 0
                ? getCurrentAndNextHourTimesObj.end[1]
                : item.time.split("-")[1]
              : "",
        });
      });
      loading();
      let { data } = await orderSubmit({
        orderShopList,
      });
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        console.log(data);
        this.orderNo = data.data.orderNo;
        setStorage("carRef", 1);
        this.payOrder();
      }
    },
    gourl(url) {
      go(url);
    },
    async payOrder() {
      let payClient = "";
      let payType = "WX";
      let appId = "";
      let codes = "";
      // #ifdef H5
      appId = config.appId;
      if (getEnv() == "H5") {
        payClient = this.payClient.H5;
      }
      if (getEnv() == "WX_PUBLIC") {
        payClient = this.payClient.WECHAT;
      }
      // #endif
      // #ifdef MP-WEIXIN
      appId = config.MPappId;
      payClient = this.payClient.MINIAPP;
      let { code } = await uni.login();
      codes = code;
      // #endif
      let { data } = await payOrder({
        appId,
        code: codes,
        orderNo: this.orderNo,
        param: "",
        payClient,
        payType,
        returnUrl: "",
      });
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        console.log(data);
        let info = data.data;
        if (info == "true") {
          uni.redirectTo({
            url: `/pages/goods/payCallBack?type=1&money=${this.info.totalPreferential2}`,
          });
        } else {
          if (payClient == this.payClient.WECHAT) {
            pays(
              JSON.parse(info),
              (res) => {
                msg("支付成功", true);
                this.ispaySuccess = true;
                uni.redirectTo({
                  url: `/pages/goods/payCallBack?type=1&money=${this.info.totalPreferential2}`,
                });
              },
              () => {
                uni.redirectTo({
                  url: `/pages/order/list?t=0`,
                });
              }
            );
          }
          if (payClient == this.payClient.MINIAPP) {
            requestPayment(JSON.parse(info))
              .then((res) => {
                msg("支付成功", true);
                this.ispaySuccess = true;
                uni.redirectTo({
                  url: `/pages/goods/payCallBack?type=1&money=${this.info.totalPreferential2}`,
                });
              })
              .catch((err) => {
                uni.redirectTo({
                  url: `/pages/order/list?t=0`,
                });
              });
          }
        }
      } else {
        uni.redirectTo({
          url: `/pages/order/list?t=0`,
        });
      }
    },
    addressInfoChange(info) {
      this.info.sellerCartList[this.sellerAddressIndex].sellerAddressInfo =
        info;
      this.sellerAddressShow = false;
    },
    openLocation(item, index) {
      this.addressList = this.info.sellerCartList[index].sellerAddressList;
      this.sellerAddressShow = true;
      this.sellerAddressIndex = index;
    },
    changeHandler(e, i) {
      const {
        columnIndex,
        value,
        values, // values为当前变化列的数组内容
        index,
        // 微信小程序无法将picker实例传出来，只能通过ref操作
        picker = this.$refs["uPicker" + i][0],
      } = e;
      // 当第一列值发生变化时，变化第二列(后一列)对应的选项
      if (columnIndex === 0) {
        // picker为选择器this实例，变化第二列对应的选项
        picker.setColumnValues(
          1,
          this.info.sellerCartList[i].columnData[i][index]
        );
      }
    },
    // 回调参数为包含columnIndex、value、values
    confirm(e, index) {
      console.log("confirm", e);
      console.log(e.values[0][e.indexs[0]]);
      console.log(e.values[1][e.indexs[1]]);
      let date = e.values[0][e.indexs[0]];
      let time = e.values[1][e.indexs[1]];
      if (!time) {
        return msg("请选择时间段");
      }
      this.info.sellerCartList[index].date = date;
      this.info.sellerCartList[index].time = time;
      this.dateShowHideChange(index);
    },

    dateShowChange(item, index) {
      this.info.sellerCartList[index].dateShow = true;
    },

    dateShowHideChange(index) {
      this.info.sellerCartList[index].dateShow = false;
    },
  },
};
</script>
<style>
/* #ifdef MP-WEIXIN */
page {
  background: #f5f5f5;
}

/* #endif */
</style>
<style lang="scss" scoped>
page {
  background: #f5f5f5;
}

.infobox1 {
  border-radius: 28rpx;
  background: #fff;
  padding: 32rpx 24rpx;
  margin: 30rpx 30rpx 0;

  .block1 {
  }

  image {
    width: 32rpx;
    height: 32rpx;
  }
}

.infobox11 {
  border-radius: 28rpx;
  background: #fff;
  padding: 32rpx 24rpx;
  margin: 30rpx 30rpx 0;

  .block1 {
    .tip1 {
    }

    .tip2 {
      margin: 24rpx 0 0;

      .tip22 {
        margin-left: 16rpx;
      }
    }
  }

  image {
    width: 32rpx;
    height: 32rpx;
  }
}

.infobox2 {
  padding: 32rpx 24rpx;
  background: #fff;
  border-radius: 28rpx;
  margin: 30rpx 30rpx 0;

  .block1 {
    margin: 0 0 34rpx 0;

    .icon1 {
      width: 40rpx;
      height: 40rpx;
    }

    .name {
      margin: 0 12rpx 0 8rpx;
    }

    .icon2 {
      width: 32rpx;
      height: 32rpx;
    }
  }

  .block2 {
    .list {
      margin: 0 0 32rpx 0;

      image {
        width: 152rpx;
        height: 152rpx;
        border-radius: 28rpx;
      }

      .info1 {
        width: calc(100% - 152rpx - 20rpx);
        margin-left: 20rpx;

        .tipbox1 {
          .tip1 {
            width: 400rpx;
          }

          .tip2 {
          }
        }

        .tipbox2 {
          margin: 16rpx 0 0;
        }

        .tipbox3 {
          margin: 21rpx 0 0;

          .tip1 {
          }

          .tip2 {
            border-radius: 40rpx;
            border: 1px solid #ccc;
            padding: 21rpx 34rpx;
          }
        }
      }
    }
  }

  .block3 {
    .info1 {
    }

    .info2 {
      image {
        width: 32rpx;
        height: 32rpx;
        margin-left: 8rpx;
      }
    }
  }

  .block4 {
    margin: 24rpx 0 0;
    border-radius: 28rpx;
    background: #f5f5f5;
    padding: 28rpx 24rpx;

    .info1 {
      width: calc(100% - 100rpx);

      .tip1 {
      }

      .tip2 {
        margin-top: 12rpx;
      }
    }
  }

  .block5 {
    margin: 40rpx 0 0;

    .info1 {
    }

    .info2 {
      image {
        width: 32rpx;
        height: 32rpx;
        margin-left: 8rpx;
      }
    }

    .textarea {
      border-radius: 28rpx;
      background: #f5f5f5;
      padding: 28rpx 24rpx;
      margin: 24rpx 0 0;
      height: calc(200rpx - 24rpx - 24rpx);

      textarea {
        width: 100%;
        height: 100%;
      }
    }
  }

  .block6 {
    margin: 24rpx 0 0;
    background: #f5f5f5;
    border-radius: 28rpx;
    padding: 14rpx 24rpx;

    .cell {
      padding: 14rpx 0;

      .info1 {
      }

      .info2 {
        image {
          width: 32rpx;
          height: 32rpx;
          margin-left: 8rpx;
        }
      }
    }
  }
}

.infobox3 {
  padding: 20rpx 24rpx;
  background: #fff;
  border-radius: 28rpx;
  margin: 30rpx 30rpx 0;

  .block1 {
    padding: 14rpx 0;

    .info1 {
    }

    .info2 {
      image {
        width: 32rpx;
        height: 32rpx;
        margin-left: 8rpx;
      }
    }
  }

  .block2 {
    margin: 14rpx 0 0;
  }

  .block3 {
    border-radius: 16rpx;
    background: #f5f5f5;
    padding: 24rpx;
    margin: 24rpx 0;

    input {
      width: 80%;
    }
  }

  .block6 {
    margin: 10rpx 0 30rpx;
    background: #f5f5f5;
    border-radius: 28rpx;
    padding: 14rpx 24rpx;

    .cell {
      padding: 14rpx 0;

      .info1 {
      }

      .info2 {
        image {
          width: 32rpx;
          height: 32rpx;
          margin-left: 8rpx;
        }
      }
    }
  }
}

.infobox4 {
  position: fixed;
  background: #fff;
  width: 100%;
  padding: 14rpx 0 50rpx;
  bottom: 0;
  z-index: 99;

  .right {
    .block1 {
      .info1 {
        .tip1 {
        }

        .tip2 {
        }
      }

      .info2 {
        text-align: right;
      }
    }

    .block2 {
      margin-left: 20rpx;
      margin-right: 30rpx;
      background: var(--view-theme);
      padding: 20rpx 54rpx;
      border-radius: 63rpx;
    }
  }
}

.popbox1 {
  background: #fff;
  border-radius: 30rpx 30rpx 0 0;
  position: relative;

  .close {
    width: 44rpx;
    height: 44rpx;
    position: absolute;
    right: 30rpx;
    top: 40rpx;
  }

  .block1 {
    padding: 36rpx 0;
    text-align: center;
  }

  .block2 {
    margin: 50rpx 0rpx 0 30rpx;

    .label {
      border-radius: 18rpx;
      border: 2rpx solid #f5f5f5;
      padding: 17rpx 0rpx;
      display: inline-block;
      margin: 0 20rpx 20rpx 0;
      width: 210rpx;
      text-align: center;
    }

    .active {
      border: 2rpx solid var(--view-theme);
      background: var(--view-minorColorT);
    }
  }

  .block3 {
    background: #f5f5f5;
    padding: 30rpx 30rpx 0;
    height: 55vh;
    overflow-y: scroll;
    // margin: 30rpx 0rpx 0 30rpx;

    .list {
      padding: 20rpx 32rpx;
      background: #fff;
      border-radius: 28rpx;
      margin: 0 0 24rpx 0;

      .left {
        width: 160rpx;
        text-align: center;

        .price {
          color: #1f1f1f;
          font-weight: bold;

          .unit {
            font-size: 40rpx;
          }

          .num {
            font-size: 64rpx;
          }
        }

        .price1 {
          font-size: 24rpx;
          color: #1f1f1f;
        }

        .label {
          margin: 16rpx auto 0;
          color: var(--view-theme);
          font-size: 24rpx;
          border-radius: 10rpx;
          border: 2rpx solid var(--view-theme);
          background: var(--view-minorColorT);
          width: 140rpx;
          height: 42rpx;
          line-height: 42rpx;
          text-align: center;
        }
      }

      .border {
        border-left: 2rpx dashed #858585;
        width: 2rpx;
        height: 160rpx;
        margin: 0 20rpx;
      }

      .right {
        width: calc(100% - 160rpx - 44rpx);

        .couponinfo {
          width: 350rpx;

          .name {
            color: #1f1f1f;
            font-size: 32rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .time {
            color: #525252;
            font-size: 24rpx;
            margin: 24rpx 0 0;
          }

          .log {
            color: #525252;
            font-size: 24rpx;
            margin-top: 8rpx;

            span {
              margin-left: 4rpx;
            }
          }
        }

        .couponbtn {
          // border-radius: 40rpx;
          // background: var(--view-theme);
          // display: flex;
          // padding: 12rpx 40rpx;
          // justify-content: center;
          // align-items: center;
          // gap: 10rpx;
          // color: #fff;
          // font-size: 24rpx;
          // margin-left: 40rpx;
        }
      }
    }
  }

  .btn {
    background: var(--view-theme);
    border-radius: 44rpx;
    margin: 30rpx 75rpx 0;
    padding: 24rpx 0;
    text-align: center;
  }
}
</style>
